//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  TableManagerViewController.m
//  PokerHandUp
//
//  Created by psvn047 on 6/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#import "TableManagerViewController.h"
#import "Deck.h"
#import "AppDelegate.h"
#import "CardView.h"
#import <QuartzCore/QuartzCore.h>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@interface TableManagerViewController ()
{// collect cards
    NSMutableArray * rivalCardArr;
    NSMutableArray * myCardArr;
    NSMutableArray * turnCardArr;
}
@property(nonatomic,retain) NSMutableArray * rivalCardArr;
@property(nonatomic,retain) NSMutableArray * myCardArr;
@property(nonatomic,retain) NSMutableArray * turnCardArr;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation TableManagerViewController
@synthesize tableCallback = _tableCallback;
@synthesize rivalCardArr =_rivalCardArr;
@synthesize myCardArr = _myCardArr;
@synthesize turnCardArr = _turnCardArr;

#define RIVAL_CARD @"rCard"
#define MY_CARD @"mCard"
#define TABLE_CARD  @"tCard"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// constants that won't change call to call
 CGFloat duration = 0.3;
 CGSize  cardSize = {42,63};
 CGPoint playerTo = {151, 100};
 CGPoint dealerTo = {151, 295};
 CGPoint turnTo = {50, 200};
long totalMoney = 0;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        rivalCardArr = [[NSMutableArray alloc] init];
        myCardArr = [[NSMutableArray alloc] init];
        turnCardArr = [[NSMutableArray alloc] init];
    }
    return self;
}
-(void) addMoney:(long) money
{
    if(money <= 0)
    {
        lblMoney.text = @"";
    }
    else 
    {
        totalMoney += money;
        lblMoney.text = [NSString stringWithFormat:@"Total $%d",totalMoney];
    }
    [self.view addSubview:lblMoney];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
-(NSArray*) getCardViews:(NSArray*) array typeCard:(NSString*) cCard
{
    NSMutableArray * resultArr = [NSMutableArray array];
    CardView * cardView;
    for (Card * card in array)
    {
        cardView =  [[CardView alloc] initWithFrame:CGRectMake(278, 200, cardSize.width, cardSize.height)];
        [cardView initData:card typeCard:cCard];
        [cardView setImage:[[[AppDelegate sharedController] deck] backImage]];
        [cardView setHighlightedImage: [card image]];
        [cardView setHighlighted:NO];
        
        if ([cardView typeCard] == RIVAL_CARD) {
           [UIView animateWithDuration:0.0f animations:^{
               cardView.transform = CGAffineTransformMakeRotation(M_PI);
            } ];
        }

        [resultArr addObject:cardView];
    }
    return resultArr;
}
-(void) clearCards
{
    if([rivalCardArr count]) 
        [rivalCardArr removeAllObjects];
    if([myCardArr count]) 
        [myCardArr removeAllObjects];
    if([turnCardArr count]) 
        [turnCardArr removeAllObjects];
    
    for (UIView *view in self.view.subviews) {
        if([view isKindOfClass:[CardView class]])
        {
            CardView* card = (CardView*) view;
            [card stopAnimation];
            [view release];
        }
        [view removeFromSuperview];
    }
}
-(void) startRound
{
    playerTo.x = 151;
    dealerTo.x = 151;
    turnTo.x = 50;
    totalMoney = 0;
    [self clearCards];
}

-(void) deal2CardTurn:(NSArray*) rivalCards myCards:(NSArray*) myCards dealer:(BOOL) isMyPlayer
{
    rivalCards = [self getCardViews:rivalCards typeCard:RIVAL_CARD];
    [rivalCardArr addObjectsFromArray:rivalCards];
    
    myCards = [self getCardViews:myCards typeCard:MY_CARD];
    [myCardArr addObjectsFromArray:myCards];

    NSArray * result;
    if(isMyPlayer)
    {
        result = [NSArray arrayWithObjects: [rivalCardArr objectAtIndex:0],[myCardArr objectAtIndex:0],[rivalCardArr objectAtIndex:1],[myCardArr objectAtIndex:1],nil];
    }   
    else {
         result = [NSArray arrayWithObjects: [myCardArr objectAtIndex:0],[rivalCardArr objectAtIndex:0],[myCardArr objectAtIndex:1],[rivalCardArr objectAtIndex:1],nil];
    }
    [self performSelectorOnMainThread:@selector(animateDealWithArray:) withObject:result waitUntilDone:YES];
}

-(void) dealFlopTurn:(NSArray*) cards
{
    cards = [self getCardViews:cards typeCard:TABLE_CARD];
    [turnCardArr addObjectsFromArray:cards];    
    [self performSelectorOnMainThread:@selector(animateDealWithArray:) withObject:cards waitUntilDone:YES];
}
-(void) dealTurnTurn:(NSArray*) cards
{
    cards = [self getCardViews:cards typeCard:TABLE_CARD];
    [turnCardArr addObjectsFromArray:cards];    
    [self performSelectorOnMainThread:@selector(animateDealWithArray:) withObject:cards waitUntilDone:YES];
}
-(void) dealRiverTurn:(NSArray*) cards
{
    cards = [self getCardViews:cards typeCard:TABLE_CARD];
     [turnCardArr addObjectsFromArray:cards];       
    [self performSelectorOnMainThread:@selector(animateDealWithArray:) withObject:cards waitUntilDone:YES];
}
// show all card
-(void) dealEndTurn
{
    for(CardView* cardView in rivalCardArr)
    {
        [cardView playAnimation];
    }
 
    //[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(animationWinPlayer) userInfo:nil repeats:NO];
}
-(void) animationWinPlayer:(NSArray*) array
{
    NSMutableArray * myCardView = [NSMutableArray array];
    [myCardView addObjectsFromArray:myCardArr];
    [myCardView addObjectsFromArray:turnCardArr];
    for(Card* card in array)
    {
        for(CardView* cardView in myCardView)
        {
            if([card rank] == [cardView.card rank] && [card suit] == [cardView.card suit])
            {
                [cardView winAnimation];
                break;
            }
        }
    }
}
-(void) animationClosePlayer:(NSArray*) array
{
    NSMutableArray * myCardView = [NSMutableArray array];
    [myCardView addObjectsFromArray:rivalCardArr];
    [myCardView addObjectsFromArray:turnCardArr];
    for(Card* card in array)
    {
        for(CardView* cardView in myCardView)
        {
            if([card rank] == [cardView.card rank] && [card suit] == [cardView.card suit])
            {
                [cardView winAnimation];
                break;
            }
        }
    }
}
- (void)animateDealWithArray:(NSArray *)array {

    // Figure out if the first object (the one we're currently using) is a player or dealer card
    CardView* cardView = (CardView*) [array objectAtIndex:0] ;
    
    if ([cardView typeCard] == RIVAL_CARD) {
        // Player card, so show the "face"
        
        [self.view addSubview:cardView];
        [UIView animateWithDuration:duration delay:0.0f options:UIViewAnimationCurveEaseIn
                         animations:^{
                             [cardView setFrame:CGRectMake(playerTo.x, playerTo.y, cardSize.width, cardSize.height)];
                             playerTo.x += cardSize.width + 3;
                         }
                         completion:^(BOOL finished) {
                             //[cardView playAnimation];
                             [self dealNext:array];
                             
                         }
         ];
    } 
    
    else if ([cardView typeCard] == MY_CARD) 
    {
        // Dealer card, so show the back
       
        [self.view addSubview:cardView];
        [UIView animateWithDuration:duration delay:0.0f options:UIViewAnimationCurveEaseIn
                         animations:^{
                             [cardView setFrame:CGRectMake(dealerTo.x, dealerTo.y, cardSize.width, cardSize.height)];
                             dealerTo.x += cardSize.width +3;
                         }
                         completion:^(BOOL finished) {
                             [cardView playAnimation];
                             [self dealNext:array];
                             
                         }
         ];
    }
    
    else if ([cardView typeCard] == TABLE_CARD){
        // Dealer card, so show the back
        [self.view addSubview:cardView];
         [UIView animateWithDuration:duration delay:0.0f options:UIViewAnimationCurveEaseIn
                         animations:^{
                             [cardView setFrame:CGRectMake(turnTo.x, turnTo.y, cardSize.width, cardSize.height)];
                            turnTo.x += cardSize.width +3;
                         }
                         completion:^(BOOL finished) {
                             [cardView playAnimation];
                             [self dealNext:array];
                             
                         }
         ];
        
    }
}
- (void)dealNext:(NSArray *)array {
    int count = [array count];
    if (count > 1) {
        NSArray *newArray = [array subarrayWithRange:NSMakeRange(1, count - 1)];
        [self animateDealWithArray:newArray];
    }
    else {
        [self performSelector:@selector(callbackDealCardComplete) withObject:nil afterDelay:2];
    }
}
// delay callback
-(void) callbackDealCardComplete
{
    [self.tableCallback dealTurnComplete];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.tableCallback = nil;
    [myCardArr release];
    [rivalCardArr release];
    [turnCardArr release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////